package com.loadmore.schedule

import android.os.Bundle
import android.view.MenuItem
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.loadmore.common.App
import com.loadmore.common.base.BaseAdapter
import com.loadmore.common.base.BaseListFragment
import com.loadmore.common.model.MessageEvent
import com.loadmore.common.model.Schedule
import com.loadmore.common.router.Router
import com.loadmore.common.router.RouterPath
import com.loadmore.schedule.adapter.ScheduleListAdapter
import com.loadmore.schedule.constants.ScheduleEventAction

@Route(path = RouterPath.Schedule)
class ScheduleFragment:BaseListFragment(), BaseAdapter.BaseClickListener {
    override fun setAdapter(): BaseAdapter {
        return ScheduleListAdapter(context!!)
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_schedule
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setMenu(R.menu.fragment_schedule)
        adapter.setClickListener(this)
        val schedules = App.daoSession.getDao(Schedule::class.java).loadAll()
        if (schedules != null && !schedules.isEmpty()) {
            adapter.append(schedules)
        }

    }

    override fun onMenuItemClick(menuItem: MenuItem) {
        super.onMenuItemClick(menuItem)
        when(menuItem.itemId) {
            R.id.create_schedule->{
                Router.go(RouterPath.ScheduleDetail,null)
            }
        }
    }

    override fun click(position: Int) {
        Router.go(RouterPath.ScheduleDetail,adapter.getItem(position))
    }

    override fun longClick(position: Int) {
    }


    override fun onMessageEvent(event: MessageEvent) {
        super.onMessageEvent(event)
        when(event.action) {
            ScheduleEventAction.create_schedule->{
                adapter.clear()
                val schedules = App.daoSession.getDao(Schedule::class.java).loadAll()
                if (schedules != null && !schedules.isEmpty()) {
                    adapter.append(schedules)
                }
            }
            ScheduleEventAction.delete_schedule->{

                adapter.clear()
                val schedules = App.daoSession.getDao(Schedule::class.java).loadAll()
                if (schedules != null && !schedules.isEmpty()) {
                    adapter.append(schedules)
                }
            }
        }
    }

}